<template>
  <view class="edit-info">
    <view class="flex-box center align-center p-3">
      <button class="avatar-wrapper" :plain="true" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
        <image class="avatar" :src="user.avatar" mode="aspectFill"></image>
        <view class="font2">请选择用户头像</view>
      </button>
    </view>
    <view class="nickname">
      <input class="input" @blur="nicknameBlur" name="nickname" type="nickname" placeholder="请输入昵称" maxlength="10"
             :value="user.nickname" />
    </view>
    <button class="submit-btn" form-type="submit" type="primary" @click="submitBtnClick">
      修改
    </button>
  </view>
</template>

<script>
  import {
    callWithErrorHandling,
    reactive,
    ref
  } from "vue";
  import {
    onLoad,
    onShow
  } from "@dcloudio/uni-app";
  import {
    setUserAvatar,
    setUserNickName,
    getUserInfo
  } from "@/store/user";
  import {
    getFileExtension,
    isValidUsername
  } from "../../utils/tools.js";
  import {
    getTodayDateString,
    getTodayMonthString
  } from '../../utils/common.js';
  import {
    getUserOpenId
  } from '../../utils/getOpenId.js';
  import md5 from 'js-md5';
  import {
    getTotalUserScore,
    getUserScoreFromCloud,
    saveUserTotalScoreToCloud,
    getUserScore,
    addUserScore,
    saveUserAddScoreToLocal,
    SignInGetScore,
    SignInGetScoreLocal,
    saveUserCloudScoreToLocal
  } from '../../store/scoreManager.js';

  export default {
    data() {
      return {
        user: {
          // 这里可以根据实际情况初始化user对象里具体属性的初始值，比如头像、昵称等
          avatar: '',
          nickname: ''
        },
        openId: ""
      };
    },
    onShow() {
      this.getUserScoreFromCloud().then((userInfo) => {
        this.user = userInfo;
      });
    },
    methods: {
      nicknameBlur(e) {
        this.user.nickname = e.detail.value;
      },
      handleEditNickname(e) {
        const db = uniCloud.database();
        if (e.detail.value.nickname && e.detail.value.nickname.length > 0) {
          this.user.nickname = e.detail.value.nickname;
          this.getUserOpenId().then((openid) => {
            const userInfo = db.collection("open_user").doc(this.user._id).update({
              nickName: e.detail.value.nickname,
              avatar: this.user.avatar
            });
          });
        } else {
          uni.showToast({
            title: "请输入昵称",
            icon: "none"
          });
        }
      },
      onChooseAvatar(e) {
        uni.showLoading({
          title: "上传中",
        });

        const {
          avatarUrl
        } = e.detail;
        this.user.avatar = avatarUrl;
        const time = new Date().getTime();
        this.getUserOpenId().then((openid) => {
          this.openId = openid;
          const uploadPath = "/resource/guaguale/user/header/" + this.openId + "-" + time + "." + this.getFileExtension(
            avatarUrl);
          uniCloud.uploadFile({
            filePath: avatarUrl,
            cloudPath: uploadPath,
            cloudPathAsRealPath: true,
            success: (res) => {
              this.user.avatar = res.fileID;
              uni.hideLoading();
            },
            fail: (err) => {
              uni.hideLoading();
              const uploadURL =
                "https://mp-b4609b89-f010-4b4d-8ed3-0087451c83a0.cdn.bspapp.com" + uploadPath;
              this.user.avatar = uploadURL;
            }
          });
        });
      },
      async submitBtnClick() {
        if (!this.user.nickname || this.user.nickname.length < 3) {
          uni.showToast({
            title: "用户昵称至少3个字符",
            icon: "none"
          });
          return;
        }
        if (this.isValidUsername(this.user.nickname) === false) {
          uni.showToast({
            title: "用户昵称不合法，不支持符号等特殊字符",
            icon: "none"
          });
          return;
        }

        uni.showLoading({
          title: "修改中...",
          mask: true,
        });
        const db = uniCloud.database();
        const updateuserdate = this.getTodayMonthString();
        db.collection("open_user").doc(this.user._id).update({
          nickname: this.user.nickname,
          avatar: this.user.avatar,
          updateuserdate
        }).then((e) => {
          uni.showToast({
            title: "修改成功！",
            icon: "none"
          });
          setTimeout(() => {
            uni.reLaunch({
              url: '/pages/index/loading'
            });
          }, 1000);
        }).catch((e) => {
          uni.hideLoading();
          uni.showToast({
            title: "修改失败，请稍后再试",
            icon: "none"
          });
        });
      },
      getUserScoreFromCloud() {
        return getUserScoreFromCloud();
      },
      getUserOpenId() {
        return getUserOpenId();
      },
      getFileExtension(url) {
        return getFileExtension(url);
      },
      isValidUsername(name) {
        return isValidUsername(name);
      },
      getTodayDateString() {
        return getTodayDateString();
      },
      getTodayMonthString() {
        return getTodayMonthString();
      }
    }
  };
</script>

<style lang="scss">
 .edit-info {
    width: 100%;
    height: 100%;
    box-sizing: border-box;

   .avatar-wrapper {
      margin-top: 100rpx;
      background-color: #fff;
      border: 0 none;
      line-height: 1.5;

     .avatar {
        width: 180rpx;
        height: 180rpx;
        border-radius: 50%;
        border: 1rpx solid rgba(255, 255, 255, 0.3);
        background-color: #ddd;
      }
    }

   .nickname {
      box-sizing: border-box;
      margin-top: 50rpx;
      height: 100rpx;
      margin-left: 50rpx;
      margin-right: 50rpx;
      position: relative;
      border: 1rpx solid #ccc;
      align-items: center;
      border-radius: 20rpx;
      // padding: 20rpx 20rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: flex-start;

     .input {
        margin-left: 30rpx;
        margin-right: 30rpx;
        width: 100%;
        height: 100%;
      }
    }

   .submit-btn {
      margin-top: 50rpx;
      margin-left: 50rpx;
      margin-right: 50rpx;
      height: 100rpx;
    }
  }
</style>